from rest_framework import serializers
from ..models import *
from datetime import datetime


# 商品信息
class FaKuyouGoodsSerializer(serializers.ModelSerializer):
    # 显示字段
    status_display = serializers.CharField(source='get_status_display', read_only=True, help_text='状态显示')
    goods_type_display = serializers.CharField(source='get_goods_type_display', read_only=True,
                                               help_text='商品类型显示')

    # 图片处理
    goods_image_url = serializers.SerializerMethodField(help_text='商品主图URL')
    goods_images_list = serializers.SerializerMethodField(help_text='商品图集列表')

    class Meta:
        model = FaKuyouGoods
        fields = '__all__'
    def get_goods_image_url(self, obj):
        """处理商品主图URL"""
        if obj.goods_image:
            return f"/media/{obj.goods_image}"
        return None

    def get_goods_images_list(self, obj):
        """处理商品图集"""
        if obj.goods_images:
            return [f"/media/{img.strip()}" for img in obj.goods_images.split(',') if img.strip()]
        return []

    def validate(self, data):
        """数据验证"""
        # 价格验证
        price_fields = ['market_sell_price', 'wholesale_price', 'vip_price']
        for field in price_fields:
            if field in data and data[field] < 0:
                raise serializers.ValidationError({field: "价格不能为负数"})

        # 库存验证
        if 'inventory' in data and data['inventory'] < 0:
            raise serializers.ValidationError({"inventory": "库存不能为负数"})

        # 折扣率验证
        if 'discount' in data and (data['discount'] < 0 or data['discount'] > 100):
            raise serializers.ValidationError({"discount": "折扣率必须在0-100之间"})

        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        # 处理SET标签
        if instance.tag:
            ret['tag'] = instance.tag.split(',') if ',' in instance.tag else [instance.tag]
        else:
            ret['tag'] = []
        return ret


# 商品分类信息
class FaKuyouGoodsTypeSerializer(serializers.ModelSerializer):

    # 图片URL处理
    image_url = serializers.SerializerMethodField()

    class Meta:
        model = FaKuyouGoodsType
        fields = '__all__'


    def get_image_url(self, obj):
        """处理图片URL"""
        if obj.supplier_type_image:
            from django.conf import settings
            return f"{settings.MEDIA_URL}{obj.supplier_type_image}"
        return None

    def validate(self, data):
        """自定义验证"""
        # 禁止设置自己为父分类
        if 'pid' in data and self.instance and data['pid'] == self.instance.id:
            raise serializers.ValidationError({
                'pid': '不能设置自己为父分类'
            })

        # 分类名称不能为空
        if 'supplier_type_name' in data and not data['supplier_type_name'].strip():
            raise serializers.ValidationError({
                'supplier_type_name': '分类名称不能为空'
            })

        return data
